package liuch.threadUtil;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author 17101651
 * @ClassName CountDownLatchTest
 * @Description countDownLatch的数量和线程的数量一定要一直，不然整个会阻塞
 * currentThreadName:pool-1-thread-2
 * currentThreadName:pool-1-thread-1
 * main ThreadName:main
 * main线程会等待其他子线程执行完毕后再开始自己后面的任务
 * @data 2018年08月15日
 */
public class CountDownLatchTest {
    public static void main(String[] args) {

        final CountDownLatch countDownLatch = new CountDownLatch(2);

        ExecutorService executorService = Executors.newFixedThreadPool(2);
        for (int i = 0; i < 2; i++) {
            executorService.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(1000L);
                        System.out.println("currentThreadName:" + Thread.currentThread().getName());
                        countDownLatch.countDown();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
        executorService.shutdown();
        try {
            countDownLatch.await();
            System.out.println("main ThreadName:" + Thread.currentThread().getName());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
